﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Kelper.Domain.Models;
using Kelper.Domain.Data.Abstract;
using Kelper.Infrastructure.Filters;
using Kelper.ViewModels;

namespace Kelper.Controllers
{
    [ValidateInput(false)]
    public class SearchController : BaseController
    {
        private const int MaxIngredientSuggestions = 15;

        private IRecipeRepository recipes;
        private IIngredientRepository ingredients;

        public SearchController(IRecipeRepository recipes, IIngredientRepository ingredients)
        {
            this.recipes = recipes;
            this.ingredients = ingredients;
        }

        public ViewResult Regular(string q, int page = 1)
        {
            if (q == null)
                return View((object)null);

            IEnumerable<RecipeSearchResult> result = recipes.Search(q);
            IEnumerable<RecipeSearchResult> subset = Paginate(result, page);

            return View(new RegularSearchViewModel
            {
                Recipes = subset,
                Query = q,
                CurrentPage = page,
                TotalItems = result.Count(),
                ItemsPerPage = PageSize
            }); 
        }

        public ViewResult Index(IList<Ingredient> ingredients)
        {
            ViewData["ingredients"] = String.Join(", ", ingredients.Select(i => i.Name));

            return View(new SearchViewModel
            {
                PopularIngredients = GetPopularIngredients(),
                SearchedIngredients = new HashSet<string>(ingredients.Select(i => i.Name))
            });
        }

        public PartialViewResult OnlyRecipes(IList<Ingredient> ingredients)
        {
            return PartialView(GetResults(ingredients));
        }

        private OnlyRecipesViewModel GetResults(IList<Ingredient> ingredients)
        {
            return new OnlyRecipesViewModel(
                recipes
                .Search(ingredients.Select(i => i.Name).ToList())
                .Take(50)   // Let's limit the results to the most relevant hits (no paging needed!)
                .GroupBy(r => r.Priority));
        }

        private IEnumerable<Ingredient> GetPopularIngredients()
        {
            return ingredients.GetMostPopular(MaxIngredientSuggestions);
        }
    }
}
